import React, { useEffect, useState } from 'react'

import routes from './routes'//引入路由表
import { RouterType } from '../interFace'

import { Route, BrowserRouter, Routes, Navigate, useLocation } from 'react-router-dom'
import Cookie from 'js-cookie'


const Index = () => {

    // 路由拦截
    const BeforeEach = (routes: any) => {
        const location = useLocation()
        // 获取token
        const token = Cookie.get('token')
        // 如果token不存在
        if (!token) {
            //即将要跳转的路径不是login页面  并且 即将要跳转的路径不是register页面  就跳转login
            if (location.pathname !== '/login' && location.pathname !== '/register') {
                return <Navigate to={'/login'}></Navigate>
            }
        }
        // if (token && location.pathname === '/login') {
        //     return <Navigate to={'/'}></Navigate>
        // }


        return routes.children
    }




    // 渲染路由
    const routerView = (routes: RouterType[]) => {
        return routes.map((v, i) => {
            return v.path
                ? <Route key={i} path={v.path} element={<BeforeEach>{v.element}</BeforeEach>}>
                    {
                        v.children && routerView(v.children)
                    }
                </Route>
                : <Route key={i} path={v.from} element={<Navigate to={v.to as string}></Navigate>} ></Route>
        })
    }


    return (
        <BrowserRouter>
            <Routes>
                {
                    routerView(routes)
                }
            </Routes>
        </BrowserRouter>
    )
}
export default Index